package services

import (
	"TaskAssignmentSystem/internal/admin/dao"
	"TaskAssignmentSystem/pkg/db/mysql"
	"TaskAssignmentSystem/pkg/timehandler"
	"TaskAssignmentSystem/pkg/utils"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"math"
	"strings"
	"time"
)

type SystemOrderService struct {
}

const (
	OrderTypeCash       = 1
	OrderTypeCashStr    = "1"
	OrderTypeProduct    = 2
	OrderTypeProductStr = "2"

	OrderReviewRecordTypeApply   = 0
	OrderReviewRecordTypePass    = 1
	OrderReviewRecordTypeRefusal = 2

	OrderReviewDefaultReviewDesc = "兑换申请"
)

func (s *SystemOrderService) OrderCreate(id uint, param map[string]string) (res string, err error) {
	var userServers UserService
	//校验用户是否存在
	exist, user, err := userServers.VerifyAndQueryUser(id)
	if err != nil {
		return res, err
	}
	if !exist {
		return res, errors.New("该用户不存在")
	}

	var order dao.SystemOrder
	order.UserId = user.UserId
	if order.Balance, err = utils.StringToFloat64(param["balance"]); err != nil {
		return res, errors.New("芝草数量异常")
	}
	if user.Balance < order.Balance {
		return res, errors.New("账户芝草数量不足")
	}
	order.ProductId = param["product_id"]

	var prodService SystemProductService
	prod, err := prodService.ProductFindByProductId(order.ProductId)
	if err != nil {
		return res, errors.New(fmt.Sprintf("产品[%v]不存在", order.ProductId))
	}
	if prod.Status != ProductOnline {
		return res, errors.New(fmt.Sprintf("产品[%v]未上架，不能兑换", order.ProductId))
	}
	var orderId = ""
	var productName = ""
	orderType := param["order_type"]
	if orderType == OrderTypeCashStr {
		if user.IsAuthentication == UserIsAuthenticationFalse || utils.StringIsEmpty(user.AlipayAccount) || utils.StringIsEmpty(user.Phone) {
			return res, errors.New(fmt.Sprintf("依据国家劳务报酬所得税报税要求，需先完成实名认证并填写手机号与支付宝号码才能进行提现"))
		}
		orderId += "CASH"
		order.OrderType = OrderTypeCash
		if order.TotalAmount, err = utils.StringToFloat64(param["total_amount"]); err != nil {
			return res, errors.New("兑换总金额异常")
		}
		if order.TaxAmount, err = utils.StringToFloat64(param["tax_amount"]); err != nil {
			return res, errors.New("纳税金额异常")
		}
		if order.ReceivedAmount, err = utils.StringToFloat64(param["received_amount"]); err != nil {
			return res, errors.New("到账金额异常")
		}
		//校验到账金额
		if order.TotalAmount < order.ReceivedAmount {
			return res, errors.New("到账金额不能超过兑换总金额")
		}
		//先不考虑小数
		/*
			if order.TotalAmount != math.Round(order.ReceivedAmount+order.TaxAmount) {
				return res, errors.New("到账金额 = 兑换总金额 - 纳税金额")
			}
		*/
		//校验税金
		var serve SystemDictService
		if taxAmount, err := serve.GetTaxAmount(user.UserId, order.TotalAmount); err != nil {
			return res, err
		} else {
			if taxAmount != order.TaxAmount {
				return res, errors.New(fmt.Sprintf("纳税金额输入错误！兑换总额为%v，纳税金额应该为%v", order.TotalAmount, taxAmount))
			}
		}
		//先不考虑小数
		totalBalance := math.Round((prod.ProductPrice * order.TotalAmount))
		if order.Balance != totalBalance {
			return res, errors.New(fmt.Sprintf("兑换错误！芝草兑换现金比例为%v:1，您兑换%v元，需要%v芝草！", prod.ProductPrice, order.TotalAmount, totalBalance))
		}
	} else if orderType == OrderTypeProductStr {
		orderId += "PROD"
		order.OrderType = OrderTypeProduct
		if order.Number, err = utils.StringToInt(param["number"]); err != nil {
			return res, errors.New("兑换数量异常")
		}
		productName = prod.ProductName
		if prod.ProductNumber < order.Number {
			return res, errors.New(fmt.Sprintf("兑换错误！商品[%v]剩余兑换数量为%v件，您兑换%v件，兑换失败！", productName, prod.ProductNumber, order.Number))
		}
		//先不考虑小数
		totalBalance := math.Round((prod.ProductPrice * float64(order.Number)))
		if order.Balance != totalBalance {
			return res, errors.New(fmt.Sprintf("兑换错误！商品[%v]兑换单价为%v芝草，您兑换%v件，需要%v芝草，兑换失败！", productName, prod.ProductPrice, order.Number, totalBalance))
		}
	} else {
		return res, errors.New("订单类型异常")
	}
	orderId += utils.UintToString(id)
	orderId += time.Now().Format("20060102150405")
	order.OrderId = orderId
	order.Remark = param["remark"]

	//创建订单
	var orderDao dao.Common[dao.SystemOrder]
	if err := orderDao.CreateOne(order).Error; err != nil {
		return res, err
	}
	var title = ""
	if orderType == OrderTypeCashStr {
		title = fmt.Sprintf("【%v元现金】", order.TotalAmount)
	} else if orderType == OrderTypeProductStr {
		title = fmt.Sprintf("【%v %v个】", productName, order.Number)
	}
	var balanceRemark = fmt.Sprintf("-%.f芝草", order.Balance)
	//创建订单兑换记录
	if err := s.OrderReviewRecordCreate(order.UserId, order.OrderId, title, balanceRemark); err != nil {
		return res, errors.New(fmt.Sprintf("创建订单兑换记录失败"))
	}
	//物品有兑换数量限制
	if orderType == OrderTypeProductStr {
		if err = prodService.UpdateNumberSubtract(order.ProductId, order.Number); err != nil {
			return res, err
		}
	}
	//创建产品订单快照
	var snapshotService SystemOrderProductSnapshotService
	if err = snapshotService.SaveSnapshot(order.OrderId); err != nil {
		return res, err
	}
	//修改用户芝草余额
	if err = userServers.UpdateBalanceSubtract(id, order.Balance); err != nil {
		return res, err
	}
	//记录用户芝草余额变动log
	var logService UserBalanceLogService
	remark := fmt.Sprintf("%s%s%s%s%s", "兑换", title, "，消耗", utils.Float64ToString(order.Balance), "芝草")
	if err = logService.AddConsumptionLog(orderId, remark); err != nil {
		return res, err
	}
	return orderId, nil
}

func (s *SystemOrderService) OrderReviewRecordCreate(userId, orderId, title, balanceRemark string) error {
	var orderRecord dao.SystemOrderReviewRecord
	orderRecord.UserId = userId
	orderRecord.OrderId = orderId
	orderRecord.Title = title
	orderRecord.BalanceRemark = balanceRemark
	orderRecord.Status = OrderReviewRecordTypeApply
	orderRecord.ReviewDesc = OrderReviewDefaultReviewDesc
	orderRecord.ReadStatus = 0
	var orderRecordDao dao.Common[dao.SystemOrderReviewRecord]
	if err := orderRecordDao.CreateOne(orderRecord).Error; err != nil {
		return err
	}
	return nil
}

func (s *SystemOrderService) OrderReviewRecordInfo(orderId string) (dao.SystemOrderReviewRecord, error) {
	var commonDao dao.Common[dao.SystemOrderReviewRecord]
	return commonDao.First(map[string]interface{}{"order_id": orderId})
}

func (s *SystemOrderService) VerifyOrderIsApply(orderId string) (bool, error) {
	var commonDao dao.Common[dao.SystemOrderReviewRecord]
	if count, err := commonDao.Count(map[string]interface{}{"order_id": orderId, "status": OrderReviewRecordTypeApply}); err != nil {
		return false, err
	} else {
		if count == 0 {
			return false, nil
		} else {
			return true, nil
		}
	}
}

func (s *SystemOrderService) VerifyOrderIsRejection(orderId string) (bool, error) {
	var commonDao dao.Common[dao.SystemOrderReviewRecord]
	if count, err := commonDao.Count(map[string]interface{}{"order_id": orderId, "status": OrderReviewRecordTypeRefusal}); err != nil {
		return false, err
	} else {
		if count == 0 {
			return false, nil
		} else {
			return true, nil
		}
	}
}

func (s *SystemOrderService) OrderInfo(orderId string) (dao.SystemOrder, error) {
	var commonDao dao.Common[dao.SystemOrder]
	return commonDao.First(map[string]interface{}{"order_id": orderId})
}

type OrderReviewRecordListResponse struct {
	dao.SystemOrderReviewRecord
	Time   string `json:"time"`
	Remark string `json:"remark"`
}

func (s *SystemOrderService) OrderReviewRecordList(sysUserId uint, page, pageSize int64, param map[string]string) (int64, []OrderReviewRecordListResponse, error) {
	var userServers UserService
	//校验用户是否存在
	exist, user, err := userServers.VerifyAndQueryUser(sysUserId)
	if err != nil {
		return 0, nil, err
	}
	if !exist {
		return 0, nil, errors.New("该用户不存在")
	}

	type SystemOrderReviewRecord struct {
		dao.SystemOrderReviewRecord
		Remark string `json:"remark"`
	}
	var serve CommonService[SystemOrderReviewRecord]
	serve.Page = page
	serve.PageSize = pageSize
	serve.Order = "tas_system_order_review_record.id desc"
	serve.WhereStr = []string{}
	serve.WhereStr = append(serve.WhereStr, fmt.Sprintf("tas_system_order_review_record.user_id = '%s'", user.UserId))
	serve.LeftJoin = append(serve.LeftJoin, fmt.Sprintf("left join tas_system_order o on tas_system_order_review_record.order_id = o.order_id"))
	sql := "tas_system_order_review_record.*,o.remark"
	serve.SelectField = &sql
	if utils.StringIsNotEmpty(param["status"]) {
		serve.WhereStr = append(serve.WhereStr, fmt.Sprintf("tas_system_order_review_record.status = %s", param["status"]))
	}
	if advList, err := serve.SelectList(); err != nil {
		return 0, nil, err
	} else {
		//var res []OrderReviewRecordListResponse
		res := make([]OrderReviewRecordListResponse, len(advList.Data))
		// 转换
		for i, v := range advList.Data {
			//item := OrderReviewRecordListResponse{SystemOrderReviewRecord: v}
			//item := *OrderReviewRecordListResponse
			res[i].Id = v.Id
			res[i].UserId = v.UserId
			res[i].OrderId = v.OrderId
			res[i].Title = v.Title + v.ReviewDesc
			res[i].Time = v.UpdatedAt.Format(timehandler.FormatLayoutTime)
			res[i].Remark = v.Remark
			res[i].BalanceRemark = v.BalanceRemark
			res[i].Status = v.Status
			res[i].ReviewDesc = v.ReviewDesc
			res[i].ReviewDetails = v.ReviewDetails
			res[i].ReadStatus = v.ReadStatus
			res[i].CreatedAt = v.CreatedAt
			/*item.Title += item.ReviewDesc
			item.Time = v.UpdatedAt.Format(timehandler.FormatLayoutTime)
			item.Remark = v.
			res = append(res, item)*/
		}
		return advList.Total, res, nil
	}
}

type AdminOrderReviewRecordListResponse struct {
	ApplyTime       time.Time `json:"apply_time"`       //申请时间
	OrderId         string    `json:"order_id"`         //订单号
	AlipayAccount   string    `json:"alipay_account"`   //支付宝账户
	Name            string    `json:"name"`             //申请人姓名
	ProductName     string    `json:"product_name"`     //商品商品名称（兑换商品时才有）
	Number          int       `json:"number"`           //申请的数量（兑换商品时才有）
	TotalAmount     float64   `json:"total_amount"`     //兑换总金额（兑换现金时才有）
	TaxAmount       float64   `json:"tax_amount"`       //税金（兑换现金时才有）
	ReceivedAmount  float64   `json:"received_amount"`  //到账金额（兑换现金时才有）
	Balance         float64   `json:"balance"`          //芝草数量
	Remark          string    `json:"remark"`           //备注
	NickName        string    `json:"nick_name"`        //昵称
	DeliveryAddress string    `json:"delivery_address"` //收货地址（兑换商品时才有）
	UserId          string    `json:"user_id"`          //用户ID
	IdCardNumber    string    `json:"id_card_number"`   //身份证号码
	Phone           string    `json:"phone"`            //手机号
	Email           string    `json:"email"`            //邮箱
	TeamNumber      string    `json:"team_number"`      //团队编号
	TeamUserName    string    `json:"team_user_name"`   //团长姓名
	TeamUserId      string    `json:"team_user_id"`     //团长ID
	TlNickName      string    `json:"tl_nick_name"`     //团长昵称
	TlEmail         string    `json:"tl_email"`         //团长邮箱
	TlPhone         string    `json:"tl_phone"`         //团长手机号
	Status          int       `json:"status"`           //状态，0：审核中 ，1：已通过，2：审核不通过
	ReviewDesc      string    `json:"review_desc"`      //审核说明
	ReviewDetails   string    `json:"review_details"`   //审核详情说明
}

func (s *SystemOrderService) AdminOrderReviewRecordList(adminUserId uint, page, pageSize int64, param map[string]string) (int64, []AdminOrderReviewRecordListResponse, error) {
	var userServers SystemAdminService
	//校验用户是否存在
	exist, _, err := userServers.VerifyAndQueryAdminUser(adminUserId)
	if err != nil {
		return 0, nil, err
	}
	if !exist {
		return 0, nil, errors.New("该用户不存在")
	}

	var commonDao dao.Common[AdminOrderReviewRecordListResponse]
	var sql = ""
	var andSql = " "
	var countSql = ""
	if utils.StringIsNotEmpty(param["name"]) {
		andSql += "AND u.real_name like '%" + param["name"] + "%' "
	}
	if utils.StringIsNotEmpty(param["user_id"]) {
		andSql += "AND u.user_id like '%" + param["user_id"] + "%' "
	}
	if utils.StringIsNotEmpty(param["team_number"]) {
		andSql += "AND u.team_number like '%" + param["team_number"] + "%' "
	}
	if utils.StringIsNotEmpty(param["apply_time_start"]) {
		andSql += "AND o.created_at >= '" + param["apply_time_start"] + " 00:00:00' "
	}
	if utils.StringIsNotEmpty(param["apply_time_end"]) {
		andSql += "AND o.created_at <= '" + param["apply_time_end"] + " 23:59:59' "
	}
	if utils.StringIsNotEmpty(param["status"]) {
		andSql += "AND r.status = " + param["status"] + " "
	}
	if utils.StringIsNotEmpty(param["alipay_account"]) {
		andSql += "AND u.alipay_account like '%" + param["alipay_account"] + "%' "
	}
	if utils.StringIsNotEmpty(param["order_id"]) {
		andSql += "AND o.order_id like '%" + param["order_id"] + "%' "
	}
	if strings.EqualFold(param["query_type"], "cash") {
		if utils.StringIsNotEmpty(param["apply_amount"]) {
			andSql += "AND o.total_amount = " + param["apply_amount"] + " "
		}
		countSql = fmt.Sprintf(
			"SELECT count(*) as total FROM tas_system_order o %v %v %v %v%d %v ",
			" LEFT JOIN tas_system_user u ON o.user_id = u.user_id ",
			" LEFT JOIN tas_system_team t ON u.team_number = t.team_number ",
			" LEFT JOIN tas_system_order_review_record r ON o.order_id = r.order_id ",
			" WHERE o.order_type = ",
			OrderTypeCash,
			andSql,
		)
		sql = fmt.Sprintf(
			"SELECT %v FROM tas_system_order o %v %v %v %v %v%d %v order by o.id desc %v ",
			" o.created_at AS apply_time,o.order_id,u.alipay_account,u.real_name AS `name`,o.total_amount,o.tax_amount,o.received_amount,o.balance,o.remark,u.nick_name,u.user_id,u.id_card_number,u.phone,u.email,u.team_number,t.user_name AS team_user_name,t.user_id AS team_user_id,r.`status`,r.review_desc,s.nick_name tl_nick_name,s.email tl_email,s.phone tl_phone,r.review_details",
			" LEFT JOIN tas_system_user u ON o.user_id = u.user_id ",
			" LEFT JOIN tas_system_team t ON u.team_number = t.team_number ",
			" LEFT JOIN tas_system_order_review_record r ON o.order_id = r.order_id ",
			" LEFT JOIN tas_system_user s ON t.user_id = s.user_id ",
			" WHERE o.order_type = ",
			OrderTypeCash,
			andSql,
			utils.Limit(page, pageSize),
		)
	} else if strings.EqualFold(param["query_type"], "product") {
		if utils.StringIsNotEmpty(param["product_name"]) {
			andSql += "AND p.product_name like '%" + param["product_name"] + "%' "
		}
		countSql = fmt.Sprintf(
			"SELECT count(*) as total FROM tas_system_order o %v %v %v %v %v%d %v ",
			" LEFT JOIN tas_system_user u ON o.user_id = u.user_id ",
			" LEFT JOIN tas_system_order_product_snapshot p ON o.id = p.order_id ",
			" LEFT JOIN tas_system_team t ON u.team_number = t.team_number ",
			" LEFT JOIN tas_system_order_review_record r ON o.order_id = r.order_id ",
			" WHERE o.order_type = ",
			OrderTypeProduct,
			andSql,
		)
		//订单关联查商品，使用快照表 tas_system_order_product_snapshot
		sql = fmt.Sprintf(
			"SELECT %v FROM tas_system_order o %v %v %v %v %v %v%d %v order by o.id desc %v ",
			" o.created_at AS apply_time,o.order_id,u.alipay_account,u.real_name AS `name`,p.product_name,o.number,o.balance,o.remark,u.nick_name,u.delivery_address,u.user_id,u.id_card_number,u.phone,u.email,u.team_number,t.user_name AS team_user_name,t.user_id AS team_user_id,r.`status`,r.review_desc,s.nick_name tl_nick_name,s.email tl_email,s.phone tl_phone,r.review_details",
			" LEFT JOIN tas_system_user u ON o.user_id = u.user_id ",
			" LEFT JOIN tas_system_order_product_snapshot p ON o.order_id = p.order_id ",
			" LEFT JOIN tas_system_team t ON u.team_number = t.team_number ",
			" LEFT JOIN tas_system_order_review_record r ON o.order_id = r.order_id ",
			" LEFT JOIN tas_system_user s ON t.user_id = s.user_id ",
			" WHERE o.order_type = ",
			OrderTypeProduct,
			andSql,
			utils.Limit(page, pageSize),
		)
	} else {
		return 0, nil, errors.New("查询类型异常")
	}
	total, err := commonDao.RawCount(countSql, "total")
	if err != nil {
		return 0, nil, err
	}
	list, err := commonDao.RawList(sql)
	if err != nil {
		return 0, nil, err
	}
	return total, list, nil
}

func (s *SystemOrderService) AdminEditOrderReviewRecord(adminUserId uint, param map[string]string) error {
	var adminUserServers SystemAdminService
	//校验用户是否存在
	exist, _, err := adminUserServers.VerifyAndQueryAdminUser(adminUserId)
	if err != nil {
		return err
	}
	if !exist {
		return errors.New("该用户不存在")
	}
	if utils.StringIsEmpty(param["order_id"]) {
		return errors.New("订单不存在")
	}
	orderId := param["order_id"]
	info, err := s.OrderReviewRecordInfo(orderId)
	if err != nil {
		return err
	}
	if utils.StringIsEmpty(param["review_desc"]) {
		return errors.New("审批意见不能为空")
	}
	if strings.EqualFold(param["up_type"], "approval") {
		err = s.OrderEditApproval(info.OrderId, info.UserId, param["review_desc"])
	} else if strings.EqualFold(param["up_type"], "rejection") {
		err = s.OrderEditRejection(info.OrderId, info.UserId, param["review_desc"])
	} else if strings.EqualFold(param["up_type"], "review_details") {
		if utils.StringIsEmpty(param["review_details"]) {
			return errors.New("审批详情不能为空")
		}
		err = s.OrderEditReviewDetails(info.OrderId, info.UserId, param["review_desc"], param["review_details"])
	} else {
		return errors.New("类型异常")
	}
	if err != nil {
		return err
	}
	return nil
}

func (s *SystemOrderService) OrderEditApproval(orderId, userId, reviewDesc string) error {
	exist, err := s.VerifyOrderIsApply(orderId)
	if err != nil {
		return err
	}
	if !exist {
		return errors.New("只有申请状态的兑换才能审批通过")
	}
	//修改为审核通过
	var commonDao dao.Common[dao.SystemOrderReviewRecord]
	commonDao.Query = map[string]interface{}{"order_id": orderId, "user_id": userId}
	err = commonDao.Update(map[string]interface{}{"status": OrderReviewRecordTypePass, "review_desc": reviewDesc}).Error
	if err != nil {
		return err
	}
	return nil
}

func (s *SystemOrderService) OrderEditRejection(orderId, userId, reviewDesc string) error {
	//校验用户是否存在
	var userService UserService
	exist, user, err := userService.VerifyAndQueryUserByUserId(userId)
	if err != nil {
		return err
	}
	if !exist {
		return errors.New("该用户不存在")
	}
	//查询订单
	order, err := s.OrderInfo(orderId)
	if err != nil {
		return err
	}
	//查产品快照
	var snapshotService SystemOrderProductSnapshotService
	prod, err := snapshotService.SnapshotFindByProductId(order.OrderId, order.ProductId)
	if err != nil {
		return err
	}
	//校验是否已拒绝
	exist, err = s.VerifyOrderIsRejection(orderId)
	if err != nil {
		return err
	}
	if exist {
		return errors.New("已拒绝的兑换，无法再审批拒绝")
	}
	//更新审批
	var commonDao dao.Common[dao.SystemOrderReviewRecord]
	commonDao.Query = map[string]interface{}{"order_id": orderId, "user_id": userId}
	if err := commonDao.Update(map[string]interface{}{"status": OrderReviewRecordTypeRefusal, "review_desc": reviewDesc, "balance_remark": gorm.Expr("CONCAT('+',substring(balance_remark,2))")}).Error; err != nil {
		return err
	}
	//返还芝草到用户
	err = userService.UpdateBalanceAdd(user.Id, order.Balance)
	if err != nil {
		return err
	}
	//记录用户芝草余额变动log
	var logService UserBalanceLogService
	var title = ""
	if order.OrderType == OrderTypeCash {
		title = fmt.Sprintf("【%v元现金】", order.TotalAmount)
	} else if order.OrderType == OrderTypeProduct {
		title = fmt.Sprintf("【%v %v个】", prod.ProductName, order.Number)
	}
	remark := fmt.Sprintf("%s%s%s%s", title, "兑换失败，返还", utils.Float64ToString(order.Balance), "芝草")
	if err = logService.AddIncomeLog(orderId, remark); err != nil {
		return err
	}
	return nil

}

func (s *SystemOrderService) OrderEditReviewDetails(orderId, userId, reviewDesc, reviewDetails string) error {
	var commonDao dao.Common[dao.SystemOrderReviewRecord]
	commonDao.Query = map[string]interface{}{"order_id": orderId, "user_id": userId}
	return commonDao.Update(map[string]interface{}{"review_desc": reviewDesc, "review_details": reviewDetails}).Error
}

func (s *SystemOrderService) ExportOrderReviewRecordList(adminUserId uint, param map[string]string) ([]AdminOrderReviewRecordListResponse, error) {
	var userServers SystemAdminService
	//校验用户是否存在
	exist, _, err := userServers.VerifyAndQueryAdminUser(adminUserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return nil, errors.New("该用户不存在")
	}

	var commonDao dao.Common[AdminOrderReviewRecordListResponse]
	var sql = ""
	var andSql = " "
	if utils.StringIsNotEmpty(param["name"]) {
		andSql += "AND u.real_name like '%" + param["name"] + "%' "
	}
	if utils.StringIsNotEmpty(param["user_id"]) {
		andSql += "AND u.user_id like '%" + param["user_id"] + "%' "
	}
	if utils.StringIsNotEmpty(param["team_number"]) {
		andSql += "AND u.team_number like '%" + param["team_number"] + "%' "
	}
	if utils.StringIsNotEmpty(param["apply_time_start"]) {
		andSql += "AND o.created_at >= '" + param["apply_time_start"] + " 00:00:00' "
	}
	if utils.StringIsNotEmpty(param["apply_time_end"]) {
		andSql += "AND o.created_at <= '" + param["apply_time_end"] + " 23:59:59' "
	}
	if utils.StringIsNotEmpty(param["status"]) {
		andSql += "AND r.status = " + param["status"] + " "
	}
	if utils.StringIsNotEmpty(param["alipay_account"]) {
		andSql += "AND u.alipay_account like '%" + param["alipay_account"] + "%' "
	}
	if utils.StringIsNotEmpty(param["user_ids"]) {
		param["user_ids"] = param["user_ids"][:len(param["user_ids"])-1]
		andSql += "AND u.user_id in (" + param["user_ids"] + ")"
	}
	if utils.StringIsNotEmpty(param["order_ids"]) {
		param["order_ids"] = param["order_ids"][:len(param["order_ids"])-1]
		andSql += "AND o.order_id in (" + param["order_ids"] + ")"
	}
	if strings.EqualFold(param["query_type"], "cash") {
		if utils.StringIsNotEmpty(param["apply_amount"]) {
			andSql += "AND o.total_amount = " + param["apply_amount"] + " "
		}
		sql = fmt.Sprintf(
			"SELECT %v FROM tas_system_order o %v %v %v %v %v%d %v ",
			" o.created_at AS apply_time,o.order_id,u.alipay_account,u.real_name AS `name`,o.total_amount,o.tax_amount,o.received_amount,o.balance,o.remark,u.nick_name,u.user_id,u.id_card_number,u.phone,u.email,u.team_number,t.user_name AS team_user_name,t.user_id AS team_user_id,r.`status`,r.review_desc,r.review_details,r.status,s.nick_name tl_nick_name,s.email tl_email,s.phone tl_phone",
			" LEFT JOIN tas_system_user u ON o.user_id = u.user_id ",
			" LEFT JOIN tas_system_team t ON u.team_number = t.team_number ",
			" LEFT JOIN tas_system_order_review_record r ON o.order_id = r.order_id ",
			" LEFT JOIN tas_system_user s ON t.user_id = s.user_id ",
			" WHERE o.order_type = ",
			OrderTypeCash,
			andSql,
		)
	} else if strings.EqualFold(param["query_type"], "product") {
		if utils.StringIsNotEmpty(param["product_name"]) {
			andSql += "AND p.product_name like '%" + param["product_name"] + "%' "
		}
		//订单关联查商品，使用快照表 tas_system_order_product_snapshot
		sql = fmt.Sprintf(
			"SELECT %v FROM tas_system_order o %v %v %v %v %v %v%d %v ",
			" o.created_at AS apply_time,o.order_id,u.alipay_account,u.real_name AS `name`,p.product_name,o.number,o.balance,o.remark,u.nick_name,u.delivery_address,u.user_id,u.id_card_number,u.phone,u.email,u.team_number,t.user_name AS team_user_name,t.user_id AS team_user_id,r.`status`,r.review_desc,r.review_details,r.status,s.nick_name tl_nick_name,s.email tl_email,s.phone tl_phone",
			" LEFT JOIN tas_system_user u ON o.user_id = u.user_id ",
			" LEFT JOIN tas_system_order_product_snapshot p ON o.order_id = p.order_id ",
			" LEFT JOIN tas_system_team t ON u.team_number = t.team_number ",
			" LEFT JOIN tas_system_order_review_record r ON o.order_id = r.order_id ",
			" LEFT JOIN tas_system_user s ON t.user_id = s.user_id ",
			" WHERE o.order_type = ",
			OrderTypeProduct,
			andSql,
		)
	} else {
		return nil, errors.New("查询类型异常")
	}
	list, err := commonDao.RawList(sql)
	if err != nil {
		return nil, err
	}
	return list, nil
}

func (s *SystemOrderService) BatchDeleteOrderInfo(ids []string) error {
	_db := mysql.GetDB()
	return _db.Transaction(func(tx *gorm.DB) error {
		var orderServ dao.Common[dao.SystemOrder]
		orderServ.Tx = tx
		var orderReviewRecordServ dao.Common[dao.SystemOrderReviewRecord]
		var orderProductSnapshotServ dao.Common[dao.SystemOrderProductSnapshot]
		var canDelIds []string
		//传了ID根据ID删除
		if len(ids) > 0 {
			//先查询可以删除的记录
			if list, err := orderReviewRecordServ.FindAll(map[string]interface{}{"status": []uint{1, 2}, "order_id": ids}); err == nil {
				for _, model := range list {
					canDelIds = append(canDelIds, model.OrderId)
				}
				if err := orderServ.RemoveUnscopedWhere(map[string]interface{}{"order_id": canDelIds}).Error; err != nil {
					return err
				} else {
					if err := orderProductSnapshotServ.RemoveUnscopedWhere(map[string]interface{}{"order_id": canDelIds}).Error; err != nil {
						return err
					} else {
						if err := orderReviewRecordServ.RemoveUnscopedWhere(map[string]interface{}{"order_id": canDelIds}).Error; err != nil {
							return err
						}
					}
				}
			}
		} else {
			//没传id删除所有的可删除订单
			if list, err := orderReviewRecordServ.FindAll(map[string]interface{}{"status": []uint{1, 2}}); err == nil {
				for _, model := range list {
					canDelIds = append(canDelIds, model.OrderId)
				}
				if err := orderServ.RemoveUnscopedWhere(map[string]interface{}{"order_id": canDelIds}).Error; err != nil {
					return err
				} else {
					if err := orderProductSnapshotServ.RemoveUnscopedWhere(map[string]interface{}{"order_id": canDelIds}).Error; err != nil {
						return err
					} else {
						if err := orderReviewRecordServ.RemoveUnscopedWhere(map[string]interface{}{"order_id": canDelIds}).Error; err != nil {
							return err
						}
					}
				}
			}
		}
		return nil
	})
}

func (s *SystemOrderService) OrderIncomeList(sysUserId string) ([]dao.SystemOrder, error) {
	var commonDao dao.Common[dao.SystemOrder]
	sql := "SELECT * FROM tas_system_order WHERE DATE_FORMAT(created_at,'%Y%m') = DATE_FORMAT(CURDATE() ,'%Y%m') and user_id = '" + sysUserId + "' and order_type=1"
	list, err := commonDao.RawList(sql)
	return list, err
}

func (s *SystemOrderService) BatchUpdateOrderReviewRecord(orderReview []dao.SystemOrderReviewRecord) error {
	_db := mysql.GetDB()
	return _db.Transaction(func(tx *gorm.DB) error {
		var orderReviewDao dao.Common[dao.SystemOrderReviewRecord]
		orderReviewDao.Tx = tx
		for _, order := range orderReview {
			updateMap := map[string]interface{}{}
			updateMap["status"] = order.Status
			updateMap["review_details"] = order.ReviewDetails
			updateMap["review_desc"] = order.ReviewDesc
			updateMap["read_status"] = order.ReadStatus
			if err := tx.Model(order).Where("order_id = ?", order.OrderId).UpdateColumns(updateMap).Error; err != nil {
				return err
			}
		}
		return nil
	})
}
